import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Description TODO
 * @Author zzj
 * @Date 2020/7/22 14:26
 */
public class UserDaoImp implements UserDao {
    private DBUtil util;
    private Connection conn;
    private PreparedStatement pst;
    private ResultSet rs;

    public void setUtil(DBUtil util) {
        this.util = util;
    }


    @Test
    @Override
    public void updateMoneyById(Integer id, Double money) throws SQLException {
        conn = util.init();
        String sql = "update bank set money = money + ? where id = ?";
        // System.out.println(sql);
        pst = conn.prepareStatement(sql);
        pst.setDouble(1, money);
        pst.setInt(2, id);
        pst.executeUpdate();
        // 这里不选择在此处关闭连接，因为事务处理还没有结束，没有commit之前再开一个连接数据不会被提交保存
    }

    @Override
    public User selectByPrimaryKey(Integer id) throws SQLException {
        User user = null;
        util.init();
        String sql = "select * from bank where id = ?";
        pst = conn.prepareStatement(sql);
        pst.setInt(1, id);
        rs = pst.executeQuery();
        while (rs.next()) {
            user = new User();
            user.setId(rs.getInt(1));
            user.setName(rs.getString(2));
            user.setMoney(rs.getDouble(3));
        }
        return user;
    }

}
